import router from './router'
import store from '@/store'
// 导入
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { asyncRouters8 } from '@/router/index'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.Token
  if (token) {
    if (to.path === '/login') {
      // 有token 在登录页就跳转到dashboard页
      next('/')
      NProgress.done()
    } else {
      const userInfo = store.state.user.userInfo.id
      if (!userInfo) {
        const res = await store.dispatch('user/getUserProfile')
        const meuns = res.data.roles.menus
        const filterRouter = asyncRouters8.filter((item) => {
          const name = item.children[0].name
          return meuns.includes(name)
        })
        console.log('111', res)
        filterRouter.push({ path: '*', redirect: '/404', hidden: true })
        // 动态添加路由
        router.addRoutes(filterRouter)
        store.commit('meun/updateMenuList', filterRouter)
        next({
          ...to,
          replace: true
        })
      } else {
        next()
      }
      // 不在登录页就放行
    }
  } else {
    // 如果没有token
    if (whiteList.includes(to.path)) {
      // 没有登录，只能去白名单(那些不需要token就可以访问的页面)
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.afterEach((to, from) => {
  NProgress.done()
})
